<?php

/**
 * WebUser based on session
 */
class WebUser extends CWebUser
{
	private $_model;

	public function getIsAdmin()
	{
		return $this->getModel()->getIsAdmin();
	}

	public function hasAccess($project, $route = null)
	{
		if ($this->isGuest) {
			return false;
		}
		return $this->getModel()->hasAccess($project, $route);
	}

	/**
	 * @return User current logined user model
	 */
	public function getModel()
	{
		if ($this->_model === null) {
			$this->_model = User::model()->findByPk($this->getId());
			if ($this->_model === null) {
				$this->logout();
				$this->loginRequired();
			}
		}
		return $this->_model;
	}

	/**
	 * Verify the cookie data before login
	 */
	protected function beforeLogin($id, $states, $fromCookie)
	{
		if ($fromCookie) {
			$identity = new UserIdentity($id, $states['password']);
			if (!$identity->authenticate($states['salt'])) {
				return false;
			}
		}
		return true;
	}

	protected function afterLogin($fromCookie)
	{
		parent::afterLogin($fromCookie);

		$model = $this->getModel();
		$request = Yii::app()->getRequest();
		// save username into cookie as default login id
		if (!$fromCookie) {
			$cookie = new CHttpCookie(LoginForm::ID_COOKIE, $model->username);
			$cookie->expire = time() + 31536000;
			$request->getCookies()->add($cookie->name, $cookie);
		}
	}
}
